import axios from 'axios';

// 封装文件上传函数

export const uploadFile = async (file: File, url: string, onProgress: (progress: number) => void) => {
    const formData = new FormData();
    formData.append('file', file);
  
    try {
      const response = await axios.post(url, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(percentCompleted);
        }
      });
  
      return response.data;
    } catch (error) {
      console.error('文件上传出错:', error);
      throw error;
    }
  };


export const downloadWithAxios = async (url: string, fileName : string ) => {
  try {
      const response = await axios({
          url,
          method: 'GET',
          responseType: 'blob' // 设置响应类型为 blob，以便处理二进制数据
      });
      
      const blob = new Blob([response.data], { type: response.headers['content-type'] });
      const urlCreator = window.URL || window.webkitURL;
      const blobUrl = urlCreator.createObjectURL(blob);

      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = fileName;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      // 释放生成的 URL 对象
      urlCreator.revokeObjectURL(blobUrl);
  } catch (error) {
      console.error('下载文件时出错:', error);
  }
};